import { AxiosInstance, AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios';

import { store } from '@/store';
import { router } from '@/router';
import { HttpUtil } from '@/utils/HttpUtil';
import { HttpModel } from '@/services/core';

/**
 * @author 戴俊明 <idaijunming@163.com>
 * @description axios Token拦截器
 * @date 2019/11/21 20:47
 **/

export interface Interceptor {
  (instance: AxiosInstance): void;
}

export const tokenInterceptor: Interceptor = (instance: AxiosInstance): void => {
  instance.interceptors.request.use(
    (config: AxiosRequestConfig) => {
      if (store.getters['account/token']) {
        // eslint-disable-next-line no-empty
        if (config.headers) {
        } else {
          config.headers = {};
        }
        config.headers.Authorization = store.getters['account/token'];
      }
      return config;
    },
    (error: AxiosError) => error
  );
  instance.interceptors.response.use(
    async (resp: AxiosResponse) => {
      // console.log(resp);
      if (resp.headers.upgrade === 'true') {
        await store.dispatch('account/upgrade');
      }
      return resp;
    },
    // 返回请求错误的响应
    async (error: AxiosError) => {
      const resp = error.response as AxiosResponse<HttpModel<never>>;
      if (resp) {
        // console.warn(resp);
        if (resp.status === 401) {
          await store.dispatch('account/logout', false);
          await router.push('/login');
          return Promise.reject(new Error('用户凭证已过期，请重新登录'));
        } else {
          return Promise.reject(new Error(HttpUtil.getMessage(resp)));
        }
      }
    }
  );
};
